layui.use(['ExTree'], function () {
    var $ = layui.$
    var url = layui.url();
    var roleId = url.search.roleId
    var exbase = layui.exbase

    var treeLoader = new layui.ExTree({
        id: "menu_tree_id",
        elem: '#menu_tree_id',
        url: ctxPath + "/admin/roles/" + roleId + "/menus/tree",
        onlyIconControl: true,
        showCheckbox: true,
        format: function (data) {
            data.title = data.name;
            data.spread = true;
            data.field = "userId"
            if(data.children && data.children.length != 0) {
                data.checked = false
            }
            return data;
        }
    })

    treeLoader.load();

    layui.form.on('submit(save_menu_tree_id)', function (data) {
        var json = exbase.getFormAsJson($(data.form))
        $.ajax({
            url: ctxPath + "/admin/roles/" + roleId + "/menus",
            method: 'POST',
            data: {userIds: json['userId']},
            success: function (data) {
                if(data.code == exbase.AJAX_SUCCESS_CODE) {
                    layer.msg("角色菜单权限配置成功")
                } else {
                    layer.msg(data.msg, {icon: 2})
                }
            }
        })

        return false
    })
})